package com.example.sprintboot.controller;

import com.example.sprintboot.common.Result;
import com.example.sprintboot.entity.Interaction;
import com.example.sprintboot.service.InteractionService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户交互控制器
 */
@RestController
@RequestMapping("/interaction")
@Tag(name = "用户交互管理", description = "用户交互相关接口（点赞、浏览、收藏、评分）")
public class InteractionController {

    @Autowired
    private InteractionService interactionService;

    /**
     * 点赞/取消点赞
     */
    @Operation(summary = "点赞/取消点赞", description = "用户对内容进行点赞或取消点赞")
    @PostMapping("/like")
    public Result toggleLike(@Parameter(description = "用户ID") @RequestParam Integer userId,
                           @Parameter(description = "内容类型") @RequestParam String contentType,
                           @Parameter(description = "内容ID") @RequestParam Integer contentId) {
        
        boolean success = interactionService.toggleLike(userId, contentType, contentId);
        if (success) {
            boolean hasLiked = interactionService.hasUserInteracted(userId, contentType, contentId, InteractionService.TYPE_LIKE);
            String message = hasLiked ? "点赞成功" : "取消点赞成功";
            
            Map<String, Object> data = new HashMap<>();
            data.put("hasLiked", hasLiked);
            data.put("likeCount", interactionService.getContentStatistics(contentType, contentId).get("likes"));
            
            return Result.success(data, message);
        } else {
            return Result.error("操作失败");
        }
    }

    /**
     * 记录浏览
     */
    @Operation(summary = "记录浏览", description = "记录用户浏览内容")
    @PostMapping("/view")
    public Result recordView(@Parameter(description = "用户ID") @RequestParam Integer userId,
                           @Parameter(description = "内容类型") @RequestParam String contentType,
                           @Parameter(description = "内容ID") @RequestParam Integer contentId) {
        
        boolean success = interactionService.recordView(userId, contentType, contentId);
        if (success) {
            Map<String, Object> data = new HashMap<>();
            data.put("viewCount", interactionService.getContentStatistics(contentType, contentId).get("views"));
            return Result.success(data, "浏览记录成功");
        } else {
            return Result.error("记录失败");
        }
    }

    /**
     * 收藏/取消收藏
     */
    @Operation(summary = "收藏/取消收藏", description = "用户对内容进行收藏或取消收藏")
    @PostMapping("/favorite")
    public Result toggleFavorite(@Parameter(description = "用户ID") @RequestParam Integer userId,
                                @Parameter(description = "内容类型") @RequestParam String contentType,
                                @Parameter(description = "内容ID") @RequestParam Integer contentId) {
        
        boolean success = interactionService.toggleFavorite(userId, contentType, contentId);
        if (success) {
            boolean hasFavorited = interactionService.hasUserInteracted(userId, contentType, contentId, InteractionService.TYPE_FAVORITE);
            String message = hasFavorited ? "收藏成功" : "取消收藏成功";
            
            Map<String, Object> data = new HashMap<>();
            data.put("hasFavorited", hasFavorited);
            data.put("favoriteCount", interactionService.getContentStatistics(contentType, contentId).get("favorites"));
            
            return Result.success(data, message);
        } else {
            return Result.error("操作失败");
        }
    }

    /**
     * 评分
     */
    @Operation(summary = "内容评分", description = "用户对内容进行评分")
    @PostMapping("/rate")
    public Result rateContent(@Parameter(description = "用户ID") @RequestParam Integer userId,
                            @Parameter(description = "内容类型") @RequestParam String contentType,
                            @Parameter(description = "内容ID") @RequestParam Integer contentId,
                            @Parameter(description = "评分（1-5）") @RequestParam Integer score) {
        
        try {
            boolean success = interactionService.rateContent(userId, contentType, contentId, score);
            if (success) {
                Map<String, Object> statistics = interactionService.getContentStatistics(contentType, contentId);
                return Result.success(statistics, "评分成功");
            } else {
                return Result.error("评分失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取内容统计信息
     */
    @Operation(summary = "获取内容统计", description = "获取内容的点赞、浏览、收藏、评分统计")
    @GetMapping("/statistics/{contentType}/{contentId}")
    public Result getContentStatistics(@Parameter(description = "内容类型") @PathVariable String contentType,
                                     @Parameter(description = "内容ID") @PathVariable Integer contentId) {
        
        Map<String, Object> statistics = interactionService.getContentStatistics(contentType, contentId);
        return Result.success(statistics);
    }

    /**
     * 获取用户对内容的交互状态
     */
    @Operation(summary = "获取用户交互状态", description = "获取用户对特定内容的交互状态")
    @GetMapping("/status")
    public Result getUserInteractionStatus(@Parameter(description = "用户ID") @RequestParam Integer userId,
                                         @Parameter(description = "内容类型") @RequestParam String contentType,
                                         @Parameter(description = "内容ID") @RequestParam Integer contentId) {
        
        Map<String, Object> status = interactionService.getUserInteractionStatus(userId, contentType, contentId);
        return Result.success(status);
    }

    /**
     * 获取用户活跃度统计
     */
    @Operation(summary = "获取用户活跃度", description = "获取用户的活跃度统计信息")
    @GetMapping("/user-activity/{userId}")
    public Result getUserActivityStatistics(@Parameter(description = "用户ID") @PathVariable Integer userId) {
        
        Map<String, Object> statistics = interactionService.getUserActivityStatistics(userId);
        return Result.success(statistics);
    }

    /**
     * 获取热门内容
     */
    @Operation(summary = "获取热门内容", description = "根据交互数据获取热门内容")
    @GetMapping("/popular/{contentType}")
    public Result getPopularContent(@Parameter(description = "内容类型") @PathVariable String contentType,
                                  @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> popularContent = interactionService.getPopularContent(contentType, limit);
        return Result.success(popularContent);
    }

    /**
     * 获取推荐内容
     */
    @Operation(summary = "获取推荐内容", description = "根据用户行为获取推荐内容")
    @GetMapping("/recommend/{userId}")
    public Result getRecommendedContent(@Parameter(description = "用户ID") @PathVariable Integer userId,
                                      @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> recommendedContent = interactionService.getRecommendedContent(userId, limit);
        return Result.success(recommendedContent);
    }

    /**
     * 分页查询所有交互记录
     */
    @Operation(summary = "分页查询交互记录", description = "分页查询所有交互记录")
    @GetMapping("/page")
    public Result getInteractionsByPage(@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                                      @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageInfo<Interaction> pageInfo = interactionService.getByPage(pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 分页查询用户交互记录
     */
    @Operation(summary = "查询用户交互记录", description = "分页查询用户的交互记录")
    @GetMapping("/user/{userId}")
    public Result getUserInteractions(@Parameter(description = "用户ID") @PathVariable Integer userId,
                                    @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                                    @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageInfo<Interaction> pageInfo = interactionService.getUserInteractionsByPage(userId, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 分页查询内容交互记录
     */
    @Operation(summary = "查询内容交互记录", description = "分页查询特定内容的交互记录")
    @GetMapping("/content/{contentType}/{contentId}")
    public Result getContentInteractions(@Parameter(description = "内容类型") @PathVariable String contentType,
                                       @Parameter(description = "内容ID") @PathVariable Integer contentId,
                                       @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                                       @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageInfo<Interaction> pageInfo = interactionService.getContentInteractionsByPage(contentType, contentId, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 分页查询指定类型的交互记录
     */
    @Operation(summary = "按类型查询交互记录", description = "分页查询指定类型的交互记录")
    @GetMapping("/type/{type}")
    public Result getInteractionsByType(@Parameter(description = "交互类型") @PathVariable Integer type,
                                      @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                                      @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageInfo<Interaction> pageInfo = interactionService.getInteractionsByTypeWithPage(type, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 条件分页查询
     */
    @Operation(summary = "条件查询交互记录", description = "根据条件分页查询交互记录")
    @GetMapping("/search")
    public Result searchInteractions(@Parameter(description = "用户ID") @RequestParam(required = false) Integer userId,
                                   @Parameter(description = "内容类型") @RequestParam(required = false) String contentType,
                                   @Parameter(description = "内容ID") @RequestParam(required = false) Integer contentId,
                                   @Parameter(description = "交互类型") @RequestParam(required = false) Integer type,
                                   @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                                   @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageInfo<Interaction> pageInfo = interactionService.searchByCondition(userId, contentType, contentId, type, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 批量记录浏览
     */
    @Operation(summary = "批量记录浏览", description = "批量记录用户浏览多个内容")
    @PostMapping("/batch-view")
    public Result batchRecordViews(@Parameter(description = "用户ID") @RequestParam Integer userId,
                                 @Parameter(description = "内容类型") @RequestParam String contentType,
                                 @Parameter(description = "内容ID列表") @RequestBody List<Integer> contentIds) {
        
        int count = interactionService.batchRecordViews(userId, contentType, contentIds);
        return Result.success("成功记录 " + count + " 条浏览记录");
    }

    /**
     * 删除交互记录
     */
    @Operation(summary = "删除交互记录", description = "根据ID删除交互记录")
    @DeleteMapping("/{id}")
    public Result deleteInteraction(@Parameter(description = "交互记录ID") @PathVariable Integer id) {
        
        boolean success = interactionService.deleteById(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 获取交互类型列表
     */
    @Operation(summary = "获取交互类型", description = "获取所有支持的交互类型")
    @GetMapping("/types")
    public Result getInteractionTypes() {
        
        Map<String, Object> types = new HashMap<>();
        types.put("1", "点赞");
        types.put("2", "浏览");
        types.put("3", "收藏");
        types.put("4", "评分");
        
        return Result.success(types);
    }
}